<template>
  <div class="page-container">
    <head-component></head-component>
    <div class="main-container">
      <aside-component></aside-component>
      <div class="content-container">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>用户管理</span>
              <div class="search-inputs">
                <el-input
                  v-model="searchQuery"
                  placeholder="用户名或电话"
                  clearable
                  style="width: 250px; margin-right: 10px;"
                  @keyup.enter="handleSearch"
                />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button type="success" @click="handleAdd" style="margin-left: 10px;">新增用户</el-button>
                <el-button
                  type="danger"
                  @click="handleBatchDelete"
                  style="margin-left: 10px;"
                  :disabled="selectedUsers.length === 0"
                >
                  批量删除 ({{ selectedUsers.length }})
                </el-button>
              </div>
            </div>
          </template>
          <el-table
            :data="users.list"
            style="width: 100%"
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="头像" width="80">
              <template #default="scope">
                <div class="avatar-wrapper">
                  <el-image
                    v-if="scope.row.avatarLoaded"
                    :src="scope.row.avatarUrl"
                   :preview-src-list="scope.row.avatarUrl ? [scope.row.avatarUrl] : []"
                    :initial-index="0"
                    fit="cover"
                    class="table-avatar"
                    :preview-teleported="true"
                    :z-index="3000"
                  >
                    <template #placeholder>
                      <div class="image-placeholder">
                        <el-icon><Loading /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <span v-else>加载中...</span>
                  <div class="avatar-hover-mask">
                    <el-icon><ZoomIn /></el-icon>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="用户名" width="100">
              <template #default="scope">
                <span v-html="highlightMatch(scope.row.name, searchQuery)"></span>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="120">
              <template #default="scope">
                <span v-html="highlightMatch(scope.row.phone, searchQuery)"></span>
              </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" width="180" />
            <el-table-column prop="address" label="地址" width="120" />
            <el-table-column prop="roleId" label="角色" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.roleId === 'adminuser' ? 'danger' : 'success'">
                  {{ scope.row.roleId === 'adminuser' ? '管理员' : '普通用户' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sex" label="性别" width="80">
              <template #default="scope">
                {{ scope.row.sex === 1 ? '男' : '女' }}
              </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄" width="100"/>
            <el-table-column prop="isLock" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isLock === 1 ? 'success' : 'danger'">
                  {{ scope.row.isLock === 1 ? '启用' : '锁定' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="100"/>
            <el-table-column prop="updateTime" label="修改时间" width="100"/>
            <el-table-column label="操作" fixed="right" width="150">
              <template #default="scope">
                <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[6, 10, 15, 20, 50]"
              :total="users.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>
    <foot-component></foot-component>
  </div>

  <!-- 编辑用户对话框 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
    <el-form :model="currentUser" :rules="editRules" ref="editUserForm" label-width="100px">
      <el-form-item label="头像" prop="headImg">
        <!-- 头像显示和上传区域 -->
        <div class="avatar-uploader" @click="triggerEditFileInput">
           <img
             v-if="currentUser.avatarUrl"
             :src="currentUser.avatarUrl"
             alt="用户头像"
             class="avatar"
           >
           <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
           <div class="avatar-hover-mask">
             <span class="upload-text">{{ currentUser.avatarUrl ? '点击更换图片' : '点击上传图片' }}</span>
           </div>
           <input
             type="file"
             ref="editFileInput"
             @change="handleEditAvatarChange"
             accept="image/jpeg,image/png"
             style="display: none"
           >
        </div>
         <div class="avatar-info">
            <p class="avatar-tip">支持 JPG、PNG 格式</p>
            <p class="avatar-tip">文件小于 2MB</p>
          </div>
      </el-form-item>
      <el-form-item label="用户名" prop="name">
        <el-input v-model="currentUser.name"></el-input>
      </el-form-item>
       <el-form-item label="密码" prop="password">
        <el-input v-model="currentUser.password" type="password" show-password></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="currentUser.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="currentUser.email"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="currentUser.address"></el-input>
      </el-form-item>
       <el-form-item label="年龄" prop="age">
        <el-input v-model.number="currentUser.age" type="number"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="currentUser.roleId" placeholder="请选择角色">
          <el-option label="管理员" value="adminuser"></el-option>
          <el-option label="普通用户" value="commonuser"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="isLock">
        <el-select v-model="currentUser.isLock" placeholder="请选择状态">
          <el-option label="启用" :value="1"></el-option>
          <el-option label="锁定" :value="0"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 修改 el-image 预览组件 -->
  <el-image
    v-if="previewImageUrl"
    :src="previewImageUrl"
    :preview-src-list="previewImageUrl ? [previewImageUrl] : []"
    :initial-index="0"
    fit="contain"
    :hide-on-click-modal="false"
    :preview-teleported="true"
    :z-index="3000"
    @close="previewImageUrl = ''"
    style="display: none;"
  />

</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import AsideComponent from '../components/Aside.vue'
import HeadComponent from '../components/Head.vue'
import FootComponent from '../components/Foot.vue'
import defaultAvatar from '@/assets/no_image.jpg'
// 引入需要的图标
import { Plus, ZoomIn, Loading } from '@element-plus/icons-vue'

export default {
  name: 'UserManger',
  components: {
    AsideComponent,
    HeadComponent,
    FootComponent,
    Plus,
    ZoomIn,
    Loading
  },

  data () {
    return {
      users: {
        total: 0,
        list: [],
        pageSize: 6,
        pageNum: 1
      },
      loading: false,
      currentPage: 1,
      pageSize: 6,
      defaultAvatar,
      dialogVisible: false,
      currentUser: {},
      dialogTitle: '',
      isAdding: false,
      pendingAvatarFile: null,
      editRules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        isLock: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        age: [
          { type: 'number', message: '年龄必须为数字值' }
        ]
      },
      searchQuery: '', // 单个搜索框的值，用于用户名或电话的模糊搜索
      previewImageUrl: '', // 添加预览图片URL
      selectedUsers: [] // 新增 selectedUsers 数据属性
    }
  },

  mounted () {
    this.getAllUser()
  },

  watch: {
    // 监听 searchQuery 变化，当为空时加载所有用户
    searchQuery (newValue, oldValue) {
      if (!newValue && oldValue) { // 从有值变为空时触发
        this.currentPage = 1 // 重置页码到第一页
        this.getAllUser()
      }
    }
  },

  methods: {
    // 异步加载单个用户头像
    async loadAvatarForUser (user) {
      user.avatarLoaded = false // 初始化加载状态
      user.avatarUrl = '' // 初始化头像 URL

      const filename = user.headImg
      if (!filename || filename.trim() === '') {
        user.avatarUrl = this.defaultAvatar
        user.avatarLoaded = true
        return
      }

      try {
        const url = `/photo/view?filename=${encodeURIComponent(filename)}`
        const response = await this.$ajax.get(url, { responseType: 'blob' })
        const reader = new FileReader()
        reader.onloadend = () => {
          user.avatarUrl = reader.result
          user.avatarLoaded = true
        }
        reader.readAsDataURL(response.data)
      } catch (error) {
        console.error('Error loading avatar:', error)
        user.avatarUrl = this.defaultAvatar
        user.avatarLoaded = true
      }
    },
    getAllUser () {
      this.loading = true
      this.$ajax.get('/admin/user/selectAllUser', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
      })
        .then((response) => {
          const resp = response.data
          if (resp.code === 0) {
            this.users = { ...resp.data }
            this.currentPage = resp.data.pageNum
            this.pageSize = resp.data.pageSize

            if (this.users.list && this.users.list.length > 0) {
              this.users.list.forEach(user => {
                this.loadAvatarForUser(user)
              })
            }
          } else {
            ElMessage.error(resp.msg)
          }
        })
        .catch((error) => {
          console.error('获取用户列表失败:', error)
          ElMessage.error('获取用户列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 根据用户名或电话搜索用户
    searchUsers () {
      // 判断搜索关键字是否为空
      if (!this.searchQuery) {
        ElMessage.warning('请输入关键字！')
        return
      }

      this.loading = true
      this.$ajax.post('/admin/user/selectByUsernameOrPhone', null, {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery
        }
      })
        .then((response) => {
          const resp = response.data
          if (resp.code === 0) {
            this.users = { ...resp.data }
            this.currentPage = resp.data.pageNum
            this.pageSize = resp.data.pageSize

            if (this.users.list && this.users.list.length > 0) {
              this.users.list.forEach(user => {
                this.loadAvatarForUser(user)
              })
            }
          } else {
            ElMessage.error(resp.msg)
          }
        })
        .catch((error) => {
          console.error('搜索用户失败:', error)
          ElMessage.error('搜索用户失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    handleSizeChange (val) {
      this.pageSize = val
      // 如果有搜索条件，则执行搜索，否则获取所有用户
      if (this.searchQuery) {
        this.searchUsers()
      } else {
        this.getAllUser()
      }
    },

    handleCurrentChange (val) {
      this.currentPage = val
      // 如果有搜索条件，则执行搜索，否则获取所有用户
      if (this.searchQuery) {
        this.searchUsers()
      } else {
        this.getAllUser()
      }
    },

    handleAdd () {
      this.dialogVisible = true
      this.dialogTitle = '新增用户'
      this.isAdding = true
      this.pendingAvatarFile = null
      // 初始化空用户数据
      this.currentUser = {
        id: null,
        name: '',
        password: '',
        phone: '',
        email: '',
        address: '',
        headImg: '',
        status: 0, // 默认启用状态
        roleId: 'commonuser', // 默认普通用户
        sex: 1, // 默认男
        age: null,
        isDelete: null,
        isLock: 1, // 默认正常状态
        createTime: null,
        updateTime: null,
        avatarUrl: this.defaultAvatar // 默认头像预览
      }
      // 重置表单验证状态
      if (this.$refs.editUserForm) {
        this.$refs.editUserForm.resetFields()
      }
    },

    handleEdit (row) {
      this.dialogVisible = true
      this.dialogTitle = '编辑用户信息'
      this.isAdding = false
      this.pendingAvatarFile = null
      // 复制用户数据到 currentUser，包括所有字段
      this.currentUser = {
        ...row, // 复制用户数据
        avatarUrl: row.avatarUrl, // 使用已经加载的头像 URL
        headImg: row.headImg || '' // 确保 headImg 字段存在
      }
      // 重置表单验证状态
      if (this.$refs.editUserForm) {
        this.$refs.editUserForm.resetFields()
      }
    },

    // 触发编辑表单中的文件输入
    triggerEditFileInput () {
      this.$refs.editFileInput.click()
    },

    // 处理编辑表单中的头像文件变化
    handleEditAvatarChange (event) {
      const fileInput = event.target
      if (!fileInput.files.length) return

      const file = fileInput.files[0]
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
        fileInput.value = ''
        return
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
        fileInput.value = ''
        return
      }

      // 存储待上传的文件
      this.pendingAvatarFile = file

      // 只进行预览
      const reader = new FileReader()
      reader.onloadend = () => {
        this.currentUser.avatarUrl = reader.result
      }
      reader.readAsDataURL(file)
      fileInput.value = '' // 清空文件输入，以便下次选择同一文件也能触发 change 事件
    },

    // 提交新增或编辑表单
    submitForm () {
      this.$refs.editUserForm.validate(async (valid) => {
        if (valid) {
          const submitData = { ...this.currentUser }

          // 先保存用户信息
          try {
            let response
            if (this.isAdding) {
              // 新增用户操作
              // 移除不需要提交的字段
              delete submitData.id
              delete submitData.avatarUrl
              delete submitData.isDelete
              delete submitData.createTime
              delete submitData.updateTime

              response = await this.$ajax.post('/admin/user/insert', submitData)
            } else {
              // 编辑用户操作
              // 如果密码字段为空，则不提交密码，避免清空用户密码
              if (submitData.password === '') {
                delete submitData.password
              }
              // 移除不需要提交的字段
              delete submitData.avatarUrl

              response = await this.$ajax.post('/admin/user/updateUserInfo', submitData)
            }

            if (response.data.code === 0) {
              // 保存用户信息成功后，立即更新当前用户的显示
              const userId = response.data.data.id || submitData.id
              const updatedUser = this.users.list.find(user => user.id === userId)
              if (updatedUser) {
                // 更新用户信息
                Object.assign(updatedUser, {
                  name: submitData.name,
                  phone: submitData.phone,
                  email: submitData.email,
                  address: submitData.address,
                  roleId: submitData.roleId,
                  sex: submitData.sex,
                  age: submitData.age,
                  isLock: submitData.isLock
                })
              }

              // 用户信息保存成功后，如果有待上传的头像文件，再上传头像
              if (this.pendingAvatarFile) {
                try {
                  const formData = new FormData()
                  formData.append('photo', this.pendingAvatarFile)

                  const uploadResponse = await this.$ajax.post('/photo/upload_photo', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' }
                  })

                  if (uploadResponse.data.code === 0) {
                    // 更新用户头像信息时，只更新 headImg 字段
                    const updateAvatarData = {
                      id: userId,
                      headImg: uploadResponse.data.data,
                      // 保持其他字段不变
                      name: submitData.name,
                      phone: submitData.phone,
                      email: submitData.email,
                      address: submitData.address,
                      roleId: submitData.roleId,
                      sex: submitData.sex,
                      age: submitData.age,
                      isLock: submitData.isLock
                    }

                    const updateResponse = await this.$ajax.post('/admin/user/updateUserInfo', updateAvatarData)

                    if (updateResponse.data.code === 0) {
                      // 更新成功后，立即更新当前用户的头像显示
                      if (updatedUser) {
                        updatedUser.headImg = uploadResponse.data.data
                        await this.loadAvatarForUser(updatedUser)
                      }
                      this.pendingAvatarFile = null // 清除待上传文件
                      ElMessage.success('用户信息和头像更新成功')
                    } else {
                      ElMessage.warning('用户信息已保存，但头像更新失败')
                    }
                  } else {
                    ElMessage.warning('用户信息已保存，但头像上传失败')
                  }
                } catch (error) {
                  console.error('头像上传失败:', error)
                  ElMessage.warning('用户信息已保存，但头像上传失败')
                }
              } else {
                ElMessage.success(this.isAdding ? '用户添加成功' : '用户信息更新成功')
              }

              this.dialogVisible = false // 关闭对话框
              // 刷新用户列表
              if (this.isAdding) {
                this.getAllUser() // 新增用户时刷新整个列表
              }
            } else {
              ElMessage.error(response.data.msg || (this.isAdding ? '用户添加失败' : '更新失败'))
            }
          } catch (error) {
            console.error(this.isAdding ? '用户添加失败:' : '更新失败:', error)
            ElMessage.error(this.isAdding ? '用户添加失败，请稍后重试' : '更新失败，请稍后重试')
          }
        }
      })
    },

    handleDelete (row) {
      ElMessageBox.confirm(
        '确定要删除该用户吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 实现删除功能
        // console.log('删除用户:', row)
        const userId = row.id // 获取用户ID
        // 将用户ID拼接到URL的查询字符串中
        this.$ajax.delete(`/admin/user/delete?id=${encodeURIComponent(userId)}`)
          .then(response => {
            const resp = response.data
            if (resp.code === 0) {
              ElMessage.success('用户删除成功')
              this.getAllUser() // 删除成功后刷新列表
            } else {
              ElMessage.error(resp.msg || '用户删除失败')
            }
          })
          .catch(error => {
            console.error('删除用户失败:', error)
            ElMessage.error('删除用户失败，请稍后重试')
          })
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    },

    // 处理搜索按钮点击和回车事件
    handleSearch () {
      this.currentPage = 1 // 搜索时重置到第一页
      this.searchUsers() // 执行搜索
    },

    // 高亮匹配的关键字
    highlightMatch (text, query) {
      if (!query) {
        return text // 没有搜索关键字直接返回原文本
      }
      const regex = new RegExp(query, 'gi') // g: 全局匹配, i: 忽略大小写
      return text.replace(regex, match => `<span style="color: red; font-weight: bold;">${match}</span>`)
    },

    handleSelectionChange (selectedRows) {
      this.selectedUsers = selectedRows.map(row => row.id)
    },

    handleBatchDelete () {
      ElMessageBox.confirm(
        `确定要删除选中的 ${this.selectedUsers.length} 个用户吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 实现批量删除功能，复用单个删除接口
        const userIds = this.selectedUsers.join(',')
        this.$ajax.delete(`/admin/user/delete?id=${encodeURIComponent(userIds)}`)
          .then(response => {
            const resp = response.data
            if (resp.code === 0) {
              ElMessage.success(`成功删除 ${this.selectedUsers.length} 个用户`)
              this.selectedUsers = [] // 清空选中的用户
              this.getAllUser() // 删除成功后刷新列表
            } else {
              ElMessage.error(resp.msg || '批量删除用户失败')
            }
          })
          .catch(error => {
            console.error('批量删除用户失败:', error)
            ElMessage.error('批量删除用户失败，请稍后重试')
          })
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
  }
}
</script>

<style>
/* 添加全局样式来移除图片预览阴影 */
.el-image-viewer__wrapper .el-image-viewer__mask {
  background-color: rgba(0, 0, 0, 0.9) !important;
}

.el-image-viewer__wrapper .el-image-viewer__canvas {
  box-shadow: none !important;
}

.el-image-viewer__wrapper .el-image-viewer__actions {
  background-color: transparent !important;
}

.el-image-viewer__wrapper .el-image-viewer__actions__inner {
  background-color: rgba(0, 0, 0, 0.5) !important;
  border-radius: 4px !important;
}
</style>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column; /* Stack children vertically */
  min-height: 100vh;
}

.main-container {
  display: flex; /* Arrange aside and content horizontally */
  flex: 1; /* Take remaining vertical space */
}

.content-container {
  flex: 1; /* Take remaining horizontal space */
  padding: 0;
  background-color: #f5f7fa;
  height: 100%;
  width: 100%;
  overflow-y: auto;
}

.box-card {
  margin-bottom: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-inputs {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* Add styles for avatar uploader in edit form */
.avatar-wrapper {
  position: relative;
  width: 50px;
  height: 50px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.table-avatar {
  width: 100%;
  height: 100%;
  border-radius: 4px;
  object-fit: cover;
}

/* 隐藏表格中 el-image 的默认 hover 效果 */
.avatar-wrapper .el-image__inner:hover {
  cursor: pointer;
}

.avatar-wrapper .el-image__inner {
  /* 确保图像完全覆盖容器 */
  display: block;
}

.avatar-uploader {
  position: relative;
  display: inline-block;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  width: 80px;
  height: 80px;
}

.avatar-uploader .avatar {
  width: 100%;
  height: 100%;
  border-radius: 4px;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 80px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-hover-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 4px;
  pointer-events: none;
}

.avatar-wrapper:hover .avatar-hover-mask,
.avatar-uploader:hover .avatar-hover-mask {
  opacity: 1;
}

.upload-text {
  color: white;
  font-size: 14px;
  text-align: center;
  padding: 0 5px;
}

.avatar-info {
  margin-top: 10px;
  font-size: 12px;
  color: #606266;
}

.avatar-tip {
  line-height: 1.5;
}

.image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
  border-radius: 4px;
}
</style>
